<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { formatDateTime } from '@vben/utils';

// 引入组件
import {
  Button,
  message,
  Popconfirm,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPayList, putPayRefund } from '#/api/plugin/pay';
import Icon from '#/components/Icons';

import { OrderDetailsModalView } from './components';

defineOptions({
  name: 'PluginPayAdminIndex',
});
const statusStr: any = {
  '-1': '关闭订单',
  '0': '未付款',
  '1': '已支付',
  '2': '已完成',
  '20': '待发货',
  '30': '待收货',
  '60': '待评价',
  '40': '已退款',
};
const statusColor = (status: number) => {
  if ([1, 2].includes(status)) {
    return 'success';
  }
  if (status === 40) {
    return 'warning';
  }
  if (status === 20) {
    return '#f50';
  }
  return 'default';
};
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
// 去除'列表'两个字
const viewTitle = routeMeta.title.replace('列表', '');
const disabledDelivery = ref(true);
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入订单号',
      },
      fieldName: 'keyword',
      label: '订单号',
    },
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: '未支付', value: 0 },
          { label: '已支付', value: 1 },
          { label: '已退款', value: 40 },
          { label: '已完成', value: 2 },
        ],
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
};
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'id', title: '编号', width: 80 },
    {
      field: 'merchantName',
      title: '商户',
      slots: { default: 'merchantName' },
      align: 'left',
    },
    {
      field: 'user',
      title: '用户',
      cellRender: { name: 'CellUser' },
      align: 'left',
    },
    { field: 'out_trade_no', title: '订单号', align: 'left' },
    { field: 'order_type', title: '订单类型', width: 120, align: 'left' },
    { field: 'amount', title: '支付金额', width: 88 },
    {
      field: 'pay_type',
      title: '支付方式',
      slots: { default: 'pay_pay_type' },
      width: 120,
    },
    {
      field: 'channel',
      title: '支付通道',
      slots: { default: 'pay_pay_channel' },
      width: 90,
    },
    { field: 'status', title: '状态', slots: { default: 'status' }, width: 90 },
    {
      field: 'pay_time',
      title: '支付时间',
      slots: { default: 'pay_time' },
      width: 150,
    },
    {
      field: 'create_time',
      title: '订单时间',
      formatter: 'formatShortDateTime',
      width: 150,
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 120,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const { data } = await getPayList({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

// 表格监听事件集
const gridEvents: VxeGridListeners<DataType> = {
  cellClick: ({ row }) => {
    disabledDelivery.value = row.status !== 20;
  },
};

// 退款操作
async function handleRefund(row: any) {
  const { msg } = await putPayRefund(row.pay);
  message.success(msg);
  GridApi.query();
}
const [OrderDetailsModal, OrderDetailsModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: OrderDetailsModalView,
  onClosed() {
    const modalData = OrderDetailsModalApi.getData();
    if (modalData.isUpdata) {
      GridApi.query();
    }
  },
});
/** 查看订单详情 */
const handleOrderDetails = () => {
  const currentRecord = GridApi.grid.getCurrentRecord();
  if (!currentRecord) {
    message.error('未选择任何行！');
    return;
  }

  OrderDetailsModalApi.setData(currentRecord);
  OrderDetailsModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <OrderDetailsModal />
    <Grid :grid-events="gridEvents" :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="handleOrderDetails()">
          <span class="anticon">
            <Icon icon="ri:information-line" />
          </span>
          订单详情
        </Button>
      </template>
      <template #merchantName="{ row }">
        {{ row.merchant.name }}
      </template>
      <template #pay_pay_type="{ row }">
        {{ row.pay.pay_type }}
      </template>
      <template #pay_pay_channel="{ row }">
        {{ row.pay.channel }}
      </template>
      <template #pay_time="{ row }">
        <span v-if="row.pay.pay_time">
          {{ formatDateTime(row.pay.pay_time * 1000) }}
        </span>
        <Tooltip v-else>
          <template #title>
            支付过期时间: {{ formatDateTime(row.expired_time * 1000) }}
          </template>
          -
        </Tooltip>
      </template>
      <template #status="{ row }">
        <Tag :color="statusColor(row.status)">{{ statusStr[row.status] }}</Tag>
      </template>
      <template #action="{ row }">
        <Space>
          <Popconfirm
            :disabled="row.status !== 1"
            cancel-text="否"
            ok-text="是"
            title="确认退款？"
            @confirm="handleRefund(row)"
          >
            <Button :disabled="row.status !== 1" type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:refresh-line" />
                </span>
              </template>
              退款
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
.qrcode-box {
  position: relative;
  width: 200px;
  height: 230px;
  padding-bottom: 20px;
  margin: 0 auto;
  text-align: center;
}

.qrcode-msg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgb(255 255 255 / 95%);
}

.msg-title {
  margin-top: 15px;
  font-size: 18px;
}

.msg-sub {
  font-size: 20px;
}
</style>
